from lly.vim.utils import try_except
from pathlib import Path
from fastapi import APIRouter, File, UploadFile, Form
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from typing import List
from starlette.responses import Response, PlainTextResponse, HTMLResponse, JSONResponse
from lly.server import root_path
from starlette.requests import Request
router = APIRouter()

file_dir = Path(root_path+'uploadfiles/')

if(not file_dir.exists()):
    file_dir.mkdir()


@router.post("/upload")
#  @try_except
#  async def create_upload_file(file: UploadFile = File(...)):
async def create_upload_files(files: List[UploadFile] = File(...)):
    for file in files:
        f = Path(file_dir / file.filename)
        contents = await file.read()
        f.write_bytes(contents)
        #  print(f.read_text())
    return {"filename": file.filename}


@router.post("/segmentUpload")
#  @try_except
async def create_upload_files(file: UploadFile = File(...), size: int = Form(...), start: int = Form(...), completed: int = Form(...)):
    f = Path(file_dir / file.filename)
    contents = await file.read()
    with f.open(mode="w+b", encoding='utf-8') as target:
        target.seek(start)
        target.write(contents)
    return {"filename": file.filename, "size": len(contents), "start": start}


@router.get("/select.html")
@try_except
def upload_file_init(request: Request):
    content = Path(f'{root_path}static/fileUpload/2.html').read_text()
    return HTMLResponse(content)
